class LevelMapView {
    constructor(container=null, character=null) {
        if (container == null || character == null){
            return;
        }
        this.container = container;
        this.character = character;
        this.currentNode = null;
        this.mapElement = null;
        this.nodeElements = new Map();
        
        // 缩放和拖动相关
        this.scale = 1;
        this.offsetX = 0;
        this.offsetY = 0;
        this.isDragging = false;
        this.lastX = 0;
        this.lastY = 0;

        // 获取已有的DOM元素
        this.gameArea = container.querySelector('.game-area');
        this.mapElement = container.querySelector('.game-map');
        this.actionPanel = container.querySelector('.action-panel');
        this.actionSection = container.querySelector('.action-section');
        this.notification = container.querySelector('.notification');

        // 初始金币
        this.character.gold = 1000;
        
        // 更新角色信息显示
        this.updateCharacterInfo();

        // 添加行动按钮事件
        this.container.querySelector('.leave-btn').onclick = () => this.leaveLevel();

        // 添加切换角色按钮事件
        this.container.querySelector('.switch-btn').onclick = () => this.switchCharacter();
    }

    createMap(levelMap) {
        // 显示加载提示
        this.showLoadingTip('正在生成地图...');
        
        // 创建SVG连线层
        const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.classList.add('map-connections');
        this.mapElement.appendChild(svg);
        
        // 递归创建节点
        this.createNodeElement(levelMap);
        this.currentNode = levelMap;
        
        // 绘制连线
        this.drawConnections(levelMap);
        
        // 更新角色位置
        this.updateCharacterPosition();
        
        // 添加事件监听
        this.setupEventListeners();
        
        // 显示初始节点的动作
        this.updateActionSection(levelMap);
        
        // 移除加载提示
        this.hideLoadingTip();
    }

    setupEventListeners() {
        // 滚轮缩放
        this.container.addEventListener('wheel', (e) => {
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            this.scale = Math.min(Math.max(0.5, this.scale * delta), 2);
            this.updateTransform();
        });

        // 拖���
        this.mapElement.addEventListener('mousedown', (e) => {
            this.isDragging = true;
            this.lastX = e.clientX;
            this.lastY = e.clientY;
        });

        window.addEventListener('mousemove', (e) => {
            if (!this.isDragging) return;
            const dx = e.clientX - this.lastX;
            const dy = e.clientY - this.lastY;
            this.offsetX += dx;
            this.offsetY += dy;
            this.lastX = e.clientX;
            this.lastY = e.clientY;
            this.updateTransform();
        });

        window.addEventListener('mouseup', () => {
            this.isDragging = false;
        });
    }

    createNodeElement(node) {
        const nodeElement = document.createElement('div');
        nodeElement.className = 'map-node';
        nodeElement.classList.add(`node-type-${node.type}`);
        nodeElement.style.left = `${node.x + this.mapElement.clientWidth/2}px`;
        nodeElement.style.top = `${node.y + 50}px`;
        
        // 添加节点图标
        const iconElement = document.createElement('div');
        iconElement.className = 'node-icon';
        nodeElement.appendChild(iconElement);
        
        // 添加提示框
        const tooltip = document.createElement('div');
        tooltip.className = 'node-tooltip';
        tooltip.textContent = `${this.getNodeTypeText(node.type)}${node.content ? ': ' + node.content.name : ''}`;
        nodeElement.appendChild(tooltip);
        
        // 添加点击事件
        nodeElement.addEventListener('click', () => this.moveToNode(node));
        
        this.mapElement.appendChild(nodeElement);
        this.nodeElements.set(node, nodeElement);
        
        // 递归处理子节点
        node.children.forEach(child => this.createNodeElement(child));
    }

    drawConnections(node) {
        const svg = this.mapElement.querySelector('.map-connections');
        node.children.forEach(child => {
            const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            line.classList.add('map-connection');
            
            const parentCenter = this.getNodeCenter(node);
            const childCenter = this.getNodeCenter(child);
            
            line.setAttribute('x1', parentCenter.x);
            line.setAttribute('y1', parentCenter.y);
            line.setAttribute('x2', childCenter.x);
            line.setAttribute('y2', childCenter.y);
            
            svg.appendChild(line);
            
            this.drawConnections(child);
        });
    }

    getNodeCenter(node) {
        const element = this.nodeElements.get(node);
        return {
            x: parseInt(element.style.left) + 20,
            y: parseInt(element.style.top) + 20
        };
    }

    updateCharacterPosition() {
        let marker = this.mapElement.querySelector('.character-marker');
        if (!marker) {
            marker = document.createElement('div');
            marker.className = 'character-marker';
            this.mapElement.appendChild(marker);
        }
        
        const currentNodeElement = this.nodeElements.get(this.currentNode);
        const rect = currentNodeElement.getBoundingClientRect();
        marker.style.left = currentNodeElement.style.left;
        marker.style.top = currentNodeElement.style.top;
    }

    moveToNode(targetNode) {
        if (!this.currentNode.children.includes(targetNode)) {
            this.showNotification('无法移动到非相邻节点');
            return;
        }

        this.currentNode = targetNode;
        this.updateCharacterPosition();
        this.updateActionSection(targetNode);
    }

    updateTransform() {
        this.mapElement.style.transform = 
            `translate(${this.offsetX}px, ${this.offsetY}px) scale(${this.scale})`;
    }

    getNodeTypeText(type) {
        switch(type) {
            case 'encounter': return '奇遇';
            case 'shop': return '商店';
            case 'battle': return '战斗';
            case 'event': return '事件';
            case 'boss': return 'BOSS';
            default: return type;
        }
    }

    showLoadingTip(text) {
        let tip = this.container.querySelector('.loading-tip');
        if (!tip) {
            tip = document.createElement('div');
            tip.className = 'loading-tip';
            this.container.appendChild(tip);
        }
        tip.textContent = text;
    }

    hideLoadingTip() {
        const tip = this.container.querySelector('.loading-tip');
        if (tip) tip.remove();
    }

    updateCharacterInfo() {
        const charInfo = this.container.querySelector('.current-character');
        const avatar = charInfo.querySelector('.character-avatar');
        const name = charInfo.querySelector('.character-name');
        const hpBar = charInfo.querySelector('.hp-bar');
        const mpBar = charInfo.querySelector('.mp-bar');
        const expBar = charInfo.querySelector('.exp-bar');

        avatar.src = this.character.images.card;
        avatar.alt = this.character.name;
        name.textContent = `${this.character.name} Lv.${this.character.level}`;

        // 更新状态条
        hpBar.querySelector('.hp-fill').style.width = `${(this.character.hp / this.character.maxHp) * 100}%`;
        hpBar.querySelector('span').textContent = `HP ${this.character.hp}/${this.character.maxHp}`;
        
        mpBar.querySelector('.mp-fill').style.width = '100%';
        mpBar.querySelector('span').textContent = 'MP 100/100';
        
        expBar.querySelector('.exp-fill').style.width = `${(this.character.exp / this.character.maxExp) * 100}%`;
        expBar.querySelector('span').textContent = `EXP ${this.character.exp}/${this.character.maxExp}`;

        // 添加金币显示
        const goldDisplay = charInfo.querySelector('.character-gold') || document.createElement('div');
        goldDisplay.className = 'character-gold';
        goldDisplay.textContent = `💰 ${this.character.gold}`;
        charInfo.appendChild(goldDisplay);
    }

    showNotification(message, type = 'error') {
        this.notification.textContent = message;
        this.notification.className = `notification ${type}`;
        this.notification.style.opacity = '1';
        
        setTimeout(() => {
            this.notification.style.opacity = '0';
        }, 2000);
    }

    updateActionSection(node) {
        this.actionSection.innerHTML = '';
        
        if (!node || !node.content) return;
        
        const actionCard = document.createElement('div');
        actionCard.className = 'action-card';
        
        switch (node.type) {
            case 'battle':
                actionCard.innerHTML = `
                    <h3>战斗！</h3>
                    <p class="node-desc">${node.content.name}</p>
                    <p class="enemy-list">敌人：${node.content.enemies.join('、')}</p>
                    <button class="action-btn battle-btn">
                        <span class="btn-icon">⚔️</span>
                        <span class="btn-text">开始战斗</span>
                    </button>
                `;
                actionCard.querySelector('.battle-btn').onclick = () => this.startBattle(node);
                break;

            case 'shop':
                actionCard.innerHTML = `
                    <h3>${node.content.name}</h3>
                    <p class="node-desc">这里可以购买各种道具</p>
                    <button class="action-btn shop-btn">
                        <span class="btn-icon">🛍️</span>
                        <span class="btn-text">进入商店</span>
                    </button>
                `;
                actionCard.querySelector('.shop-btn').onclick = () => this.openShop(node);
                break;

            case 'encounter':
                actionCard.innerHTML = `
                    <h3>奇遇！</h3>
                    <p class="node-desc">${node.content.name}</p>
                    <p class="reward-text">奖励：${node.content.reward}</p>
                    <button class="action-btn encounter-btn">
                        <span class="btn-icon">✨</span>
                        <span class="btn-text">调查</span>
                    </button>
                `;
                actionCard.querySelector('.encounter-btn').onclick = () => this.handleEncounter(node);
                break;

            case 'event':
                actionCard.innerHTML = `
                    <h3>${node.content.name}</h3>
                    <p class="node-desc">${node.content.description || ''}</p>
                    <div class="event-choices">
                        ${node.content.choices.map(choice => `
                            <button class="action-btn event-btn">
                                <span class="btn-icon">❓</span>
                                <span class="btn-text">${choice}</span>
                            </button>
                        `).join('')}
                    </div>
                `;
                actionCard.querySelectorAll('.event-btn').forEach((btn, index) => {
                    btn.onclick = () => this.handleEventChoice(node, index);
                });
                break;

            case 'boss':
                actionCard.innerHTML = `
                    <h3>BOSS战！</h3>
                    <p class="node-desc">${node.content.name}</p>
                    <p class="warning-text">⚠️ 请确保状态良好再挑战</p>
                    <button class="action-btn boss-btn">
                        <span class="btn-icon">👑</span>
                        <span class="btn-text">挑战BOSS</span>
                    </button>
                `;
                actionCard.querySelector('.boss-btn').onclick = () => this.startBossBattle(node);
                break;

            case 'merchant':
                actionCard.innerHTML = `
                    <h3>神秘商人</h3>
                    <p class="node-desc">这里有一些神秘的效果在出售...</p>
                    <button class="action-btn merchant-btn">
                        <span class="btn-icon">✨</span>
                        <span class="btn-text">查看效果</span>
                    </button>
                `;
                actionCard.querySelector('.merchant-btn').onclick = () => this.handleMerchant(node);
                break;
        }
        
        this.actionSection.appendChild(actionCard);
    }

    // 节点动作处理方法
    startBattle(node) {
        // TODO: 实现战斗系统
        this.showNotification('战斗系统开发中...', 'info');
    }

    openShop(node) {
        ShopView.show(this.character);
    }

    handleEncounter(node) {
        MysteryMerchantView.show(this.character);
    }

    handleEventChoice(node, choiceIndex) {
        // TODO: 实现事件选择系统
        this.showNotification('做出了选择...', 'info');
    }

    startBossBattle(node) {
        // TODO: 实现BOSS战斗
        this.showNotification('BOSS战斗系统开发中...', 'info');
    }

    handleMerchant(node) {
        MysteryMerchantView.show(this.character);
    }

    showInventory() {
        ModalManager.show('#inventory-modal', {
            onShow: (content) => {
                const itemsSection = document.createElement('div');
                itemsSection.className = 'inventory-section items-section active';
                itemsSection.innerHTML = this.character.inventory.length ? 
                    this.character.inventory.map(item => `
                        <div class="inventory-item">
                            <div class="item-info">
                                <h3>${item.name}</h3>
                                <p>${item.description}</p>
                            </div>
                            <button class="use-btn" data-item-id="${item.id}">使用</button>
                        </div>
                    `).join('') : 
                    '<p class="empty-tip">背包是空的</p>';
                
                content.querySelector('.inventory-sections').appendChild(itemsSection);
                
                // 添加事件处理
                content.querySelectorAll('.use-btn').forEach(btn => {
                    btn.onclick = () => {
                        const item = this.character.inventory.find(i => i.id === btn.dataset.itemId);
                        if (item) {
                            const result = item.use(this.character);
                            this.showNotification(result, 'success');
                            this.updateCharacterInfo();
                            if (item.type === ItemType.CONSUMABLE) {
                                this.character.inventory = this.character.inventory.filter(i => i !== item);
                            }
                            ModalManager.hide('.modal');
                        }
                    };
                });
            }
        });
    }

    leaveLevel() {
        ModalManager.showMessage({
            title: '确认离开',
            message: '确定要离开当前关卡吗？',
            confirmText: '确定',
            cancelText: '取消',
            showCancel: true
        }).then(result => {
            if (result) {
                // 隐藏游戏界面
                this.container.style.display = 'none';
                // 显示关卡选择界面
                document.getElementById('levelSelect').style.display = 'block';
            }
        });
    }

    switchCharacter() {
        // 获取可用角色列表
        const characters = InitialCharacters.map(id => characterManager.createCharacter(id));
        
        ModalManager.show('#character-switch-modal', {
            onShow: (content) => {
                content.querySelector('.character-list').innerHTML = characters.map(char => `
                    <div class="character-option ${char.id === this.character.id ? 'active' : ''}" data-char-id="${char.id}">
                        <img src="${char.images.card}" alt="${char.name}">
                        <div class="char-info">
                            <h3>${char.name}</h3>
                            <div class="char-stats">
                                <span>HP: ${char.hp}/${char.maxHp}</span>
                                <span>等级: ${char.level}</span>
                            </div>
                        </div>
                    </div>
                `).join('');

                content.querySelectorAll('.character-option').forEach(option => {
                    option.onclick = () => {
                        const charId = option.dataset.charId;
                        if (charId !== this.character.id) {
                            this.character = characterManager.createCharacter(charId);
                            this.updateCharacterInfo();
                            ModalManager.hide('.modal');
                            NotificationManager.success(`切换到角色：${this.character.name}`);
                        }
                    };
                });
            }
        });
    }
} 